#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h> //posix网络编程
#include <strings.h>
#include <pthread.h>
#include "../common/network/inc/Message.h"

typedef struct sockaddr_in sockaddr_in;
typedef struct sockaddr sockaddr;

int clientFd;

void* receiveMsg(void*)
{
    while (1)
    {
        // 收取客户端消息
        Message *msg = receiveMessage(clientFd);
        printf("receiver data:length=%d,contentType=%d,content=%s\n",msg->length,msg->type,msg->content);
        free(msg);
    }
}

int main(int argc, char const *argv[])
{
    //1 创建套接字文件描述符
    clientFd = socket(AF_INET,SOCK_STREAM,0);
    if(clientFd == -1)
    {
        perror("创建套接字失败");
        return -1;
    }

    //2 构建服务端地址
    sockaddr_in serverAddr;
    int addrSize = sizeof(sockaddr_in);
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(9999);
    serverAddr.sin_addr.s_addr = inet_addr("192.168.38.128");

    //3 连接服务端
    int retVal = connect(clientFd,(sockaddr*)&serverAddr,addrSize);
    if(retVal == -1)
    {
        perror("连接服务端失败!");
        return -1;
    }

    pthread_t tid;
    pthread_create(&tid,NULL,receiveMsg,NULL);

    //4 向服务端发消息
    char* msg = calloc(1,128);
    while (1)
    {
        bzero(msg,128);
        printf("请输入要发送的消息:\n");
        fgets(msg,128,stdin);
        Message msgTmp;
        msgTmp.content=0;
        msgTmp.length=strlen(msg);
        msgTmp.content = msg;
        int size = sendMessage(clientFd,&msgTmp);
        printf("发送成功，size=%d\n",size);
        //send(clientFd,msg,strlen(msg),0);
    }
    

    //5 关闭文件描述符
    close(clientFd);
    return 0;
}
